package cn.iocoder.yudao.module.contract.service.exportContract;

import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants;
import cn.iocoder.yudao.framework.common.util.number.MoneyUtil;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.contract.dal.dataobject.basicData.*;
import cn.iocoder.yudao.module.contract.dal.dataobject.client.ClientDO;
import cn.iocoder.yudao.module.contract.dal.dataobject.company.CompanyDO;
import cn.iocoder.yudao.module.contract.dal.dataobject.contractTemplate.ContractTemplateDO;
import cn.iocoder.yudao.module.contract.dal.dataobject.order.OrderDO;
import cn.iocoder.yudao.module.contract.dal.dataobject.order.OrderDetailsDO;
import cn.iocoder.yudao.module.contract.dal.mysql.order.OrderDetailsMapper;
import cn.iocoder.yudao.module.contract.service.basicData.*;
import cn.iocoder.yudao.module.contract.service.client.ClientService;
import cn.iocoder.yudao.module.contract.service.company.CompanyService;
import cn.iocoder.yudao.module.contract.service.contractTemplate.ContractTemplateService;
import cn.iocoder.yudao.module.contract.service.order.OrderService;
import cn.iocoder.yudao.module.contract.utils.DateEnFormatUtil;
import cn.iocoder.yudao.module.contract.utils.HtmlToFileConverter;
import cn.iocoder.yudao.module.contract.utils.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.C;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import cn.iocoder.yudao.module.contract.controller.admin.exportContract.vo.*;
import cn.iocoder.yudao.module.contract.dal.dataobject.exportContract.ExportContractDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.contract.dal.mysql.exportContract.ExportContractMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.contract.enums.ErrorCodeConstants.*;

/**
 * 出口合同 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
@Slf4j
public class ExportContractServiceImpl extends ServiceImpl<ExportContractMapper, ExportContractDO> implements ExportContractService {

    @Resource
    private ExportContractMapper exportContractMapper;
    @Resource
    private OrderService orderService;
    @Resource
    private OrderDetailsMapper orderDetailsMapper;
    @Resource
    private CompanyService companyService;
    @Resource
    private ContractTemplateService contractTemplateService;
    @Resource
    private ClientService clientService;
    @Resource
    private BasicBankService basicBankService;
    @Resource
    private HtmlToFileConverter htmlToFileConverter;
    @Resource
    private BasicPaymentService basicPaymentService;
    @Resource
    private BasicSupplierService basicSupplierService;
    @Resource
    private BasicBrokerageService basicBrokerageService;
    @Resource
    private BasicPackingService basicPackingService;
    @Resource
    private BasicVarietyService basicVarietyService;

    @Override
    public Long createExportContract(ExportContractSaveReqVO createReqVO) {
        // 插入
        ExportContractDO exportContract = BeanUtils.toBean(createReqVO, ExportContractDO.class);
        exportContractMapper.insert(exportContract);
        // 返回
        return exportContract.getId();
    }

    @Override
    public void updateExportContract(ExportContractSaveReqVO updateReqVO) {
        // 校验存在
        validateExportContractExists(updateReqVO.getId());
        // 更新
        ExportContractDO updateObj = BeanUtils.toBean(updateReqVO, ExportContractDO.class);
        exportContractMapper.updateById(updateObj);
    }

    @Override
    public void deleteExportContract(Long id) {
        // 校验存在
        validateExportContractExists(id);
        // 删除
        exportContractMapper.deleteById(id);
    }

    private void validateExportContractExists(Long id) {
        if (exportContractMapper.selectById(id) == null) {
            throw exception(EXPORT_CONTRACT_NOT_EXISTS);
        }
    }

    @Override
    public ExportContractDO getExportContract(Long id) {
        return exportContractMapper.selectById(id);
    }

    @Override
    public PageResult<ExportContractDO> getExportContractPage(ExportContractPageReqVO pageReqVO) {
        return exportContractMapper.selectPage(pageReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void exportContractService(ExportContractGenerateVO exportContractGenerate) {
        String[] ids = exportContractGenerate.getOrderIds().split(",");
        List<OrderDO> orderList = orderService.list(Wrappers.<OrderDO>lambdaQuery().in(OrderDO::getId, Arrays.asList(ids)));
        if(orderList.size()==0){
            throw exception("订单数据不存在");
        }
        if(ids.length!=orderList.size()){
            throw exception("订单数据异常");
        }

        Map<String, List<OrderDO>> ordersMap = orderList.stream().collect(Collectors.groupingBy(item -> item.getBukrs() + "-" + item.getKunnr()+ "-" +item.getInco1()+ "-" +item.getInco2()));
        if(ordersMap.size()>1){
            throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),"请选择售达方、公司主体、国际贸易条件相同的订单数据");
        }
        ExportContractDO exportContract = exportContractGenerate.getExportContract();

        if(ObjectUtil.isEmpty(exportContract.getId())){
            for(OrderDO orderDO : orderList){
                if(!"0".equals(orderDO.getStatus())){
                    throw exception("订单："+orderDO.getVbeln()+"已生成合同，请勿重复生成");
                }
            }
            exportContract.setCreatorUsername(SecurityFrameworkUtils.getLoginUsername());
        }else{
            ExportContractDO exportContractDO = getById(exportContract.getId());
            if(exportContractDO==null){
                throw exception("合同数据异常");
            }
        }
        List<String> vbelns = orderList.stream().map(OrderDO::getVbeln).distinct().collect(Collectors.toList());
        BasicPaymentDO basicPayment = basicPaymentService.getOne(Wrappers.<BasicPaymentDO>lambdaQuery().eq(BasicPaymentDO::getCode,exportContract.getPaymentCode()),false);
        BasicPackingDO basicPacking = basicPackingService.getOne(Wrappers.<BasicPackingDO>lambdaQuery().eq(BasicPackingDO::getCode,exportContract.getPackingCode()),false);
        BasicBankDO basicBank = basicBankService.getById(exportContract.getBankId());
        exportContract.setPaymentName(basicPayment.getValue());
        exportContract.setPackingName(basicPacking.getValue());
        exportContract.setBankName(basicBank.getBankName());
        if(StringUtils.isNotBlank(exportContract.getZzlifnr())){
            BasicSupplierDO supplier = basicSupplierService.getOne(Wrappers.<BasicSupplierDO>lambdaQuery().eq(BasicSupplierDO::getCode,exportContract.getZzlifnr()),false);
            if(supplier==null){
                throw exception("供应商："+exportContract.getZzlifnr()+"不存在");
            }
            exportContract.setZzlifnrt(supplier.getName());

        }
        BigDecimal totalMoney = BigDecimal.ZERO;
        if(exportContractGenerate.getDetailsList().size()>0){
            totalMoney = exportContractGenerate.getDetailsList().stream()
                    .filter(map -> map.getDdje() != null) // 过滤掉null值
                    .map(map -> {return new BigDecimal(map.getDdje()); // 转换为BigDecimal
                    })
                    .reduce(BigDecimal.ZERO, BigDecimal::add); // 累加
        }
        exportContract.setTotalMoney(totalMoney.toString());

        exportContract.setVbelns(String.join(",", vbelns));
        exportContract.setType("1");
        generateContractFile(exportContract,exportContractGenerate.getDetailsList());
        saveOrUpdate(exportContract);
        orderDetailsMapper.updateBatch(exportContractGenerate.getDetailsList());

        if(StringUtils.isNotBlank(exportContract.getZzlifnr())){
            //供应商不为空时生成佣金合同
            ExportContractDO exportContractDO = BeanUtils.toBean(exportContract,ExportContractDO.class);
            exportContractDO.setId(null);
            exportContractDO.setType("2");
            generateContractFile(exportContractDO,exportContractGenerate.getDetailsList());
            saveOrUpdate(exportContractDO);
        }
        exportContractGenerate.setExportContract(exportContract);
        for(OrderDO orderDO : orderList){
            orderDO.setContractNo(exportContract.getBstnk());
            orderDO.setStatus("1");
            orderService.updateById(orderDO);
        }
    }

    public void generateContractFile(ExportContractDO exportContract, List<OrderDetailsDO> detailsList)  {
        try {
            CompanyDO company = companyService.getOne(Wrappers.<CompanyDO>lambdaQuery().eq(CompanyDO::getCompanyCode,exportContract.getBukrs()));
            ContractTemplateDO contractTemplate = null;
            String contractTypeCode = "1".equals(exportContract.getType())?"Y4":"Y4-1";
            contractTemplate = contractTemplateService.getOne(Wrappers.<ContractTemplateDO>lambdaQuery().eq(ContractTemplateDO::getContractTypeCode,contractTypeCode).eq(ContractTemplateDO::getClientCode,exportContract.getKunnr()));
            if(contractTemplate==null){
                contractTemplate = contractTemplateService.getOne(Wrappers.<ContractTemplateDO>lambdaQuery().eq(ContractTemplateDO::getContractTypeCode,contractTypeCode).isNull(ContractTemplateDO::getClientId));
            }
            if(contractTemplate==null){
                throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),"合同模板不存在");
            }
            exportContract.setContractTemplateId(contractTemplate.getId());
            exportContract.setContractTemplateName(contractTemplate.getContractName());

            ClientDO clientDO = clientService.getOne(Wrappers.<ClientDO>lambdaQuery().eq(ClientDO::getClientCode,exportContract.getKunnr()),false);
            if(clientDO==null){
                throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),"未找到售达方"+exportContract.getKunnr()+"的客户信息");
            }

            String htmlContent = contractTemplate.getContractContent();
            htmlContent = htmlInit(htmlContent);
            BasicBankDO basicBankDO = basicBankService.getById(exportContract.getBankId());
            if(basicBankDO==null){
                throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),"未找到银行信息");
            }
            Map<String,Object> param = buildContractParam(exportContract,detailsList,basicBankDO,company,clientDO);
            htmlContent = HtmlToFileConverter.authHtmlToPdf(htmlContent, param);
            String fileUrl = null;
            if("1".equals(exportContract.getType())){
                fileUrl = htmlToFileConverter.htmlToWord(htmlContent,"exportContract/"+exportContract.getBstnk(),"fpht-");
            }else{
                //佣金合同，需要与出口订单合同合并
                List<String> htmlContents = new ArrayList<>();
                ExportContractDO exportContractDO = getOne(Wrappers.<ExportContractDO>lambdaQuery().eq(ExportContractDO::getBstnk,exportContract.getBstnk()).eq(ExportContractDO::getType,"1").ne(ExportContractDO::getStatus,"3"));
                if(exportContractDO==null){
                    throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),"佣金合同生成失败，未找到"+exportContract.getBstnk()+"的出口合同");
                }
                htmlContents.add(exportContractDO.getContractHtml());
                htmlContents.add(htmlContent);
                fileUrl = htmlToFileConverter.htmlToWord(htmlContents,"exportContract/"+exportContract.getBstnk(),"fpht-");
                htmlContent = StringUtils.join(htmlContents,"<div style='break-after: page;'></div><div class='page-break'>")+"</div>";
            }
            if(fileUrl==null){
                throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),"文件生成失败");
            }
//            exportContract.setGeneratedTime(LocalDateTime.now());
            exportContract.setContractHtml(htmlContent);
            exportContract.setContractFileUrl(fileUrl);
            exportContract.setStatus("2");
            exportContract.setAbnormalCause("");
        }catch (Exception e){
            exportContract.setStatus("1");
            exportContract.setAbnormalCause("合同生成失败：系统异常");
            log.error("合同生成失败-{}:",exportContract.getId(),e);
            throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),e.getMessage());
        }
    }

    /**
     * 处理富文本html
     * @param htmlContent
     * @return
     */
    private String htmlInit(String htmlContent) {
        htmlContent= htmlContent.replaceAll("\\$\\{序号}","\\$\\{orderInfo.序号}");
        htmlContent= htmlContent.replaceAll("\\$\\{行项目}","\\$\\{orderInfo.行项目}");
        htmlContent= htmlContent.replaceAll("\\$\\{产品组}","\\$\\{orderInfo.产品组}");
        htmlContent= htmlContent.replaceAll("\\$\\{产品组描述}","\\$\\{orderInfo.产品组描述}");
        htmlContent= htmlContent.replaceAll("\\$\\{产品规格}","\\$\\{orderInfo.产品规格}");
        htmlContent= htmlContent.replaceAll("\\$\\{物料号}","\\$\\{orderInfo.物料号}");
        htmlContent= htmlContent.replaceAll("\\$\\{物料描述}","\\$\\{orderInfo.物料描述}");
        htmlContent= htmlContent.replaceAll("\\$\\{旧物料号}","\\$\\{orderInfo.旧物料号}");
        htmlContent= htmlContent.replaceAll("\\$\\{订单数量}","\\$\\{orderInfo.订单数量}");
        htmlContent= htmlContent.replaceAll("\\$\\{成交单价}","\\$\\{orderInfo.成交单价}");
        htmlContent= htmlContent.replaceAll("\\$\\{加工费}","\\$\\{orderInfo.加工费}");
        htmlContent= htmlContent.replaceAll("\\$\\{订单金额}","\\$\\{orderInfo.订单金额}");
        htmlContent= htmlContent.replaceAll("\\$\\{等级}","\\$\\{orderInfo.等级}");
        htmlContent= htmlContent.replaceAll("\\$\\{备注}","\\$\\{orderInfo.备注}");
        htmlContent= htmlContent.replaceAll("\\$\\{产品质量}","\\$\\{orderInfo.产品质量}");
//        htmlContent= htmlContent.replaceAll("\\$\\{再生产品备注}","\\$\\{orderInfo.再生产品备注}");
        htmlContent= htmlContent.replaceAll("\\$\\{不含税总金额}","\\$\\{orderInfo.不含税总金额}");
        htmlContent= htmlContent.replaceAll("\\$\\{原销售订单}","\\$\\{orderInfo.原销售订单}");
        htmlContent= htmlContent.replaceAll("\\$\\{原项目}","\\$\\{orderInfo.原项目}");
        htmlContent= htmlContent.replaceAll("\\$\\{拒绝原因}","\\$\\{orderInfo.拒绝原因}");

        htmlContent= htmlContent.replaceAll("\\$\\{物料功能性}","\\$\\{orderInfo.物料功能性}");
        htmlContent= htmlContent.replaceAll("\\$\\{产品凭证货币}","\\$\\{orderInfo.产品凭证货币}");
        htmlContent= htmlContent.replaceAll("\\$\\{佣金组}","\\$\\{orderInfo.佣金组}");
        htmlContent= htmlContent.replaceAll("\\$\\{佣金金额}","\\$\\{orderInfo.佣金金额}");
        htmlContent= htmlContent.replaceAll("\\$\\{销售单位}","\\$\\{orderInfo.销售单位}");
        htmlContent= htmlContent.replaceAll("\\$\\{物料类型}","\\$\\{orderInfo.物料类型}");
        htmlContent= htmlContent.replaceAll("\\$\\{物料属性}","\\$\\{orderInfo.物料属性}");
        htmlContent= htmlContent.replaceAll("\\$\\{产品规格2}","\\$\\{orderInfo.产品规格2}");
        htmlContent= htmlContent.replaceAll("\\$\\{网络捻向}","\\$\\{orderInfo.网络捻向}");
        htmlContent= htmlContent.replaceAll("\\$\\{产品规格3}","\\$\\{orderInfo.产品规格3}");


//        htmlContent = addWatermark(htmlContent);
        Document doc = Jsoup.parse(htmlContent);
        Elements tdElements =  doc.select("td");
        for (Element cell : tdElements) {
            String text = cell.text(); // 获取td元素及其所有子元素的文本内容
            if (text.startsWith("${orderInfo")) {
                Element tr = cell.parent(); // 获取单元格的父元素
                if (tr.tagName().equals("tr")) { // 确保父元素是tr
                    Element trr = tr.parent(); // 获取单元格的父元素
                    if(!trr.tagName().equals("list")) {
                        // 创建<#list></#list>元素
                        tr.wrap("<list>");
                    }
                }
            }
        }

        htmlContent = doc.html();
        htmlContent = htmlContent.replaceAll("<list>","<#list orderDetails as orderInfo>");
        htmlContent = htmlContent.replaceAll("</list>","</#list>");
        return htmlContent;
    }

    /**
     * 构建合同变量参数
     * @return
     */
    private Map<String,Object> buildContractParam(ExportContractDO exportContract, List<OrderDetailsDO> orderDeatils, BasicBankDO basicBankDO, CompanyDO companyDO, ClientDO clientDO){

        Map<String,Object> param = new HashMap<>();
        //订单信息
        param.put("合同号码", StringUtils.nvl(exportContract.getBstnk(), ""));
        if(StringUtils.isNotBlank(exportContract.getAudat())){
            param.put("合同日期", DateEnFormatUtil.convertToCustomFormat(exportContract.getAudat()));
        }else{
            param.put("合同日期", "");
        }
        param.put("销售组织", StringUtils.nvl(exportContract.getVkorg(), ""));
        param.put("付款条件", StringUtils.nvl(exportContract.getPaymentName(), ""));
        param.put("凭证货币", StringUtils.nvl(exportContract.getWaerk(), ""));
        if(StringUtils.isNotBlank(exportContract.getVdatu())){
            param.put("装运期限", DateEnFormatUtil.convertToCustomFormat(exportContract.getVdatu()));
            param.put("凭证日期后一月", DateEnFormatUtil.convertToCustomFormat(exportContract.getVdatu(),1));
            param.put("凭证日期后三月", DateEnFormatUtil.convertToCustomFormat(exportContract.getVdatu(),2));
        }else{
            param.put("装运期限", "");
            param.put("凭证日期后一月", "");
            param.put("凭证日期后三月", "");
        }
        param.put("经销商名称", StringUtils.nvl(exportContract.getZzlifnrt(), ""));
        param.put("公司代码", StringUtils.nvl(exportContract.getBukrs(), ""));
        param.put("公司名称", StringUtils.nvl(exportContract.getButxt(), ""));
        param.put("售达方", StringUtils.nvl(exportContract.getKunnr(), ""));
        param.put("售达方描述", StringUtils.nvl(exportContract.getKname(), ""));
        param.put("贸易条件", StringUtils.nvl(exportContract.getInco1(), ""));
        param.put("贸易条件2", StringUtils.nvl(exportContract.getInco2(), ""));
        param.put("包装方式", StringUtils.nvl(exportContract.getPackingName(), ""));
        param.put("收款银行名称", StringUtils.nvl(basicBankDO.getBankName(), ""));
        param.put("收款银行地址", StringUtils.nvl(basicBankDO.getBankAddress(), ""));
        param.put("联行号", StringUtils.nvl(basicBankDO.getBankCode(), ""));
        param.put("银行账号", StringUtils.nvl(basicBankDO.getBankAccount(), ""));

        //产品信息
        List<Map<String,Object>> details = new ArrayList<>();
        BigDecimal quantityTotal= BigDecimal.ZERO;
        BigDecimal amountSum = BigDecimal.ZERO;
        BigDecimal noTaxAmountSum = BigDecimal.ZERO;
        String rebirthRemark = "";

        List<String> brokerageList = new ArrayList<>();
        List<String> varietyList = new ArrayList<>();
        for(int i=0;i<orderDeatils.size();i++){
            OrderDetailsDO orderDetailsDO = orderDeatils.get(i);
            BasicBrokerageDO brokerage = null;
            BasicVarietyDO variety = null;
            if(StringUtils.isNotBlank(orderDetailsDO.getKonda())){
                brokerage = basicBrokerageService.getOne(Wrappers.<BasicBrokerageDO>lambdaQuery().eq(BasicBrokerageDO::getCode,orderDetailsDO.getKonda()),false);
                if(brokerage==null){
                    throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),"佣金组-"+orderDetailsDO.getKonda()+"不存在");
                }
                if(!brokerageList.contains(brokerage.getValue())){
                    brokerageList.add(brokerage.getValue());
                }
            }
            if(StringUtils.isNotBlank(orderDetailsDO.getZzpz())){
                variety = basicVarietyService.getOne(Wrappers.<BasicVarietyDO>lambdaQuery().eq(BasicVarietyDO::getName,orderDetailsDO.getZzpz()),false);
                if(variety==null){
                    throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),"品种编码-"+orderDetailsDO.getZzpz()+"不存在");
                }
                if(!varietyList.contains(variety.getValue())){
                    varietyList.add(variety.getValue());
                }
            }
            Map<String,Object> data = new HashMap<>();
            data.put("序号",i+1);
            data.put("行项目", StringUtils.nvl(orderDetailsDO.getPosnr(),""));
            data.put("产品组", StringUtils.nvl(orderDetailsDO.getSpart(),""));
            data.put("产品组描述", StringUtils.nvl(orderDetailsDO.getSpartt(),""));
            data.put("产品规格", StringUtils.nvl(orderDetailsDO.getZzcpgg(),""));
            data.put("物料号", StringUtils.nvl(orderDetailsDO.getMatnr(),""));
            data.put("物料描述", StringUtils.nvl(orderDetailsDO.getArktx(),""));
            data.put("旧物料号", StringUtils.nvl(orderDetailsDO.getBismt(),""));
            data.put("订单数量", StringUtils.nvl(MoneyUtil.toSeparator(orderDetailsDO.getKwmeng()),""));
            data.put("成交单价", StringUtils.nvl(orderDetailsDO.getCjdj(),""));
            data.put("加工费", StringUtils.nvl(orderDetailsDO.getZyp(),""));
            data.put("订单金额", StringUtils.nvl(MoneyUtil.toSeparator(orderDetailsDO.getDdje()),""));
            data.put("等级", StringUtils.nvl(orderDetailsDO.getDj(),""));
            data.put("备注", StringUtils.nvl(orderDetailsDO.getZzhtibz(),""));
            data.put("产品质量", StringUtils.nvl(orderDetailsDO.getCpzl(),""));
            data.put("不含税总金额", StringUtils.nvl(MoneyUtil.toSeparator(orderDetailsDO.getNetwr()),""));
            data.put("原销售订单", StringUtils.nvl(orderDetailsDO.getZzvbeln(),""));
            data.put("原项目", StringUtils.nvl(orderDetailsDO.getZzposnr(),""));
            data.put("拒绝原因", StringUtils.nvl(orderDetailsDO.getAbgru(),""));
            data.put("物料功能性", StringUtils.nvl(orderDetailsDO.getZzwlgnx(),""));

            data.put("产品凭证货币", StringUtils.nvl(orderDetailsDO.getWaerk(),""));
            data.put("佣金组", brokerage!=null?brokerage.getValue():"");
            data.put("佣金金额", StringUtils.nvl(MoneyUtil.toSeparator(orderDetailsDO.getKwert()),""));
            data.put("销售单位", StringUtils.nvl(orderDetailsDO.getVrkme(),""));
            data.put("物料类型", StringUtils.nvl(orderDetailsDO.getMtart(),""));
            data.put("物料属性", StringUtils.nvl(orderDetailsDO.getZwlsx(),""));
            data.put("产品规格2", StringUtils.nvl(orderDetailsDO.getZzcpgg2(),""));
            data.put("产品规格3", StringUtils.nvl(orderDetailsDO.getZzcpgg3(),""));
            data.put("网络捻向", StringUtils.nvl(orderDetailsDO.getMesh(),""));

            if(StringUtils.isNotBlank(orderDetailsDO.getKwmeng())){
                quantityTotal = quantityTotal .add(new BigDecimal(orderDetailsDO.getKwmeng()));
            }
            if(StringUtils.isNotBlank(orderDetailsDO.getDdje())){
                amountSum = amountSum.add(new BigDecimal(orderDetailsDO.getDdje()));
            }
            if(StringUtils.isNotBlank(orderDetailsDO.getNetwr())){
                noTaxAmountSum = noTaxAmountSum.add(new BigDecimal(orderDetailsDO.getNetwr()));
            }
            if(StringUtils.isNotBlank(orderDetailsDO.getZscpbz())){
                rebirthRemark = orderDetailsDO.getZscpbz();
            }
            details.add(data);
        }
        param.put("orderDetails",details);

        param.put("价格组合并", brokerageList.size()>0?String.join(";", brokerageList):"");
        param.put("品种海关编码", varietyList.size()>0?String.join(";", varietyList):"");

        //产品合计
        param.put("再生产品备注",rebirthRemark);
        param.put("数量合计",MoneyUtil.toSeparator(quantityTotal.toString()));
        param.put("不含税总金额合计", StringUtils.nvl(MoneyUtil.toSeparator(noTaxAmountSum.toString()), ""));
        param.put("订单金额合计", StringUtils.nvl(MoneyUtil.toSeparator(amountSum.toString()), ""));
        param.put("合计金额大写", StringUtils.nvl(MoneyUtil.toChinese(String.valueOf(amountSum)), ""));
        //公司信息（乙方）
        param.put("供方单位名称", StringUtils.nvl(companyDO.getCompanyName(), ""));
        param.put("供方单位地址", StringUtils.nvl(companyDO.getAddress(), ""));
        param.put("供方法定代表", StringUtils.nvl(companyDO.getLegalPerson(), ""));
        param.put("供方电话", StringUtils.nvl(companyDO.getPhone(), ""));
        param.put("供方传真", StringUtils.nvl(companyDO.getFaxes(), ""));
        param.put("供方开户银行", StringUtils.nvl(companyDO.getBankName(), ""));
        param.put("供方账号", StringUtils.nvl(companyDO.getBankAccount(), ""));
        param.put("供方税号", StringUtils.nvl(companyDO.getTaxNumber(), ""));
        param.put("签订地点", StringUtils.nvl(companyDO.getSigningAddress(), ""));
        param.put("供方英文名称", StringUtils.nvl(companyDO.getEnName(), ""));
        param.put("供方英文地址", StringUtils.nvl(companyDO.getEnAddress(), ""));
        //客户信息（甲方）

        param.put("客户名称", StringUtils.nvl(clientDO.getClientName(), ""));
        param.put("客户简称", StringUtils.nvl(clientDO.getCalledForShort(), ""));
        param.put("客户电话", StringUtils.nvl(clientDO.getPhone(), ""));
        param.put("客户传真", StringUtils.nvl(clientDO.getFaxes(), ""));
        param.put("客户街道", StringUtils.nvl(clientDO.getStreet(), ""));
        param.put("客户法定代表", StringUtils.nvl(clientDO.getLegalPerson(), ""));
        param.put("客户委托代表", StringUtils.nvl(clientDO.getProxy(), ""));
        param.put("客户开户银行", StringUtils.nvl(clientDO.getBankName(), ""));
        param.put("客户开户账号", StringUtils.nvl(clientDO.getBankAccount(), ""));
        param.put("客户QQ", StringUtils.nvl(clientDO.getQqNumber(), ""));
        param.put("客户微信", StringUtils.nvl(clientDO.getWeChatNumber(), ""));
        param.put("客户收票地址", StringUtils.nvl(clientDO.getCollectionAddress(), ""));
        param.put("客户接收人姓名", StringUtils.nvl(clientDO.getReceiverName(), ""));
        param.put("客户接收人职务", StringUtils.nvl(clientDO.getReceiverDuty(), ""));
        param.put("客户接收人电话", StringUtils.nvl(clientDO.getReceiverPhone(), ""));
        param.put("街道2", StringUtils.nvl(clientDO.getStrSuppl1(), ""));
        param.put("街道3", StringUtils.nvl(clientDO.getStrSuppl2(), ""));
        return param;
    }
}